<template>
  <el-dialog width="70%" :visible="visible" :modal-append-to-body="true" @close="doClose">
    <el-container>
      <el-aside width="20%" style="background: none">
        <!--     分类选择     -->
        <el-row :gutter="20">
          <el-col :span="18">
            <el-input
              style="width: 100%"
              placeholder="过滤"
              v-model="filterText">
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button icon="el-icon-refresh" size="mini" @click="getCategories"></el-button>
          </el-col>
        </el-row>


        <el-tree
          @current-change="changCategory"
          class="filter-tree"
          :data="categories"
          :props="treeProps"
          :filter-node-method="filterNode"
          ref="tree">
        </el-tree>
      </el-aside>
      <el-main style="padding: 8px">
        <!--     查询表单     -->
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
          <el-form-item label="SKU编码" prop="skuCode">
            <el-input
              v-model="queryParams.skuCode"
              placeholder="请输入SKU编码"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="SKU名称" prop="skuName">
            <el-input
              v-model="queryParams.skuName"
              placeholder="请输入SKU名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="商品条码" prop="goodsBarcode">
            <el-input
              v-model="queryParams.goodsBarcode"
              placeholder="请输入商品条码"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          
          <!-- <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item> -->
        </el-form>
        <right-toolbar :showSearch.sync="showSearch"  @handleQuery="handleQuery" @resetQuery="resetQuery"></right-toolbar>
        <!--    sku表格      -->
        <el-table
          class="selection-none"
          max-height="350"
          :data="skuList"
          ref="table"
          v-loading="loading"
          :row-key="getRowKeys"
          @selection-change="handleSelectionChange"
          style="width: 100%">
          <!-- <el-table-column  width="35">
            <template slot-scope="scope">
              <el-radio :label="scope.row.id" v-model="id" @change="rowClick">
                {{''}}
              </el-radio>
            </template>
          </el-table-column> -->
          <el-table-column 
            type="selection" 
            width="45" 
            :reserve-selection="true"
            align="center">
          </el-table-column>
          <el-table-column
            prop="skuCode"
            label="SKU编码"
            width="300">
          </el-table-column>
          <el-table-column
            prop="skuName"
            label="SKU名称"
            width="300">
          </el-table-column>
          <el-table-column
            prop="expireDate"
            label="效期"
            width="120">
          </el-table-column>
          <el-table-column
            prop="goodsBarcode"
            label="条码"
            width="120">
          </el-table-column>
          <el-table-column
            v-if="checkStock"
            prop="warelocationName"
            label="所属库位">
          </el-table-column>
          <el-table-column
            v-if="checkStock"
            prop="availableQty"
            label="剩余库存">
          </el-table-column>
          <el-table-column
            prop="categoryName"
            label="所属分类">
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
        <el-row style="margin-top: 40px">
          <el-col align="right">
            <el-button @click="doClose">取消</el-button>
            <el-button type="primary" @click="confirmSku">确定</el-button>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </el-dialog>
</template>

<script>
  import {listInventory} from '@/api/stock/inventory'
  import {listCategory} from "@/api/goods/category";
  import {listSku} from "@/api/goods/sku";

  export default {
    name: "SkuSelector",
    props: {
      visible: Boolean,
      warehouseId: null
    },
    data() {
      return {
        filterText: '',
        categories: [],
        treeProps: {
          children: 'children',
          label: 'name'
        },
        total: 0,
        // id: null,
        skuList: [],
        loading: false,
        queryParams: {},
        showSearch: true,
        //本次选中
        curRows: []
      }
    },
    computed: {
      // 是否需要检查库存
      checkStock () {
        return this.warehouseId && this.warehouseId !== 0;
      },
      /* isSelected () {
        return this.curRow != null
      } */
    },
    watch: {
      visible: function (val) {
        if(val) {
          this.reset();
          if (!this.categories || !this.categories.length)
            this.getCategories();
          this.getList();
        }
      },
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
    methods: {
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.curRows = selection;
      },
      getRowKeys(row) {
        return this.checkStock?row.skuId+row.warelocationId+"":row.skuId
      },
      changCategory (cur) {
        this.queryParams.categoryCode = cur.code;
        this.getList();
      },
      getCategories () {
        this.filterText = '';
        listCategory({}).then(response => {
          // 避免改变源数据，建议克隆（此处浅克隆）
          const arrayCopy = response.data.map(item => Object.assign({}, item));

          // 第一步，将数组根据parentId进行分组，并以parentId为key扁平保存，同时找到根节点
          const obj = {};
          arrayCopy.forEach(item => {
            if (!obj[`${item.parentId}`]) {
              obj[`${item.parentId}`] = []
            }
            obj[`${item.parentId}`].push(item)
          });

          // 第二步，再次遍历数组，挂载自己的子节点
          arrayCopy.forEach(item => {
            if (obj[`${item.id}`]) {
              item.children = obj[`${item.id}`]
            }
          });
          this.categories = [{name:'全部分类'},...obj['0']];
        });
      },
      filterNode(value,data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      reset () {
        this.resetQuery();
        this.curRows = [];
        this.total = 0;
        this.showSearch = true;
        // this.id = null;
        this.skuList = [];
        // this.categories = [];
      },
      handleQuery(){
        this.queryParams.pageNum = 1;
        this.getList();
      },
      getList() {
        this.loading = true;
        if(this.warehouseId){
          this.queryParams.warehouseId = this.warehouseId;
        }
        let listApi = this.checkStock?listInventory:listSku;
        let queryParams = {...this.queryParams};
        if (!this.checkStock) {
          queryParams.name = queryParams.skuName;
          queryParams.code = queryParams.skuCode;
          // 0 启用 1 停用, 过滤停用Sku
          queryParams.status = 0;
        } else {
          // 0 启用 1 停用, 过滤停用库位
          queryParams.warelocationStatus = 0;
        }
        // 非销毁库位
        queryParams.notWarelocationType = -20;
        listApi(queryParams).then(response => {
          this.total = response.total;
          if (!this.checkStock) {
            response.data = response.data.map(item => {
              return {
                ...item,
                skuId: item.id,
                skuName: item.name,
                skuCode: item.code
              }
            })
          }
          this.skuList = response.data;
          this.loading = false;
        }).catch(reason => {
          this.loading = false;
        });
      },
      resetQuery() {
        this.queryParams = {
          pageSize: 20,
          pageNum: 1
        };
        this.handleQuery();
      },
      confirmSku () {
        this.$emit('selected',this.curRows);
        this.doClose()
      },
      doClose () {
        this.$emit('update:visible',false);
        this.$refs.table.clearSelection();
      }
    }
  }
</script>

<style>
  .selection-none *::-moz-selection {
    background: transparent;
    border-color: transparent;
    color: #000000;
  }

  .selection-none *::selection {
    background: transparent;
    border-color: transparent;
    color: #000000;
  }

</style>
